'use strict'

const Router = require('koa-router')
const User = require('../models/User')
const Notice = require('../models/Notice')
const helper = require('../utility/helper')

// TODO: refactor
const AES_SECRET_KEY = 'N2I2NmU3NGZiZTU5MWJiNGJlOTg0N2Y0'

const router = new Router({
  prefix: '/v1',
})

// TODO: Hypermedia API
router.get('/', async (ctx, next) => {
  ctx.body = {
    msg: '/v1 api'
  }
})

router.get('/test', async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')
  const num = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(10)
    }, 2000)
  })
  ctx.body = {
    num: num,
  }
})

router.post('/users', async (ctx, next) => {
  let { username, password } = ctx.request.body
  const existence = await User.findOne({username})
  if (existence) {
    ctx.body = {
      error: true,
      message: 'username is already existence.'
    }
    return
  }
  password = helper.encryption(password, AES_SECRET_KEY)
  const user = new User({username, password})
  ctx.body = await user.save()
})

router.post('/login', async (ctx, next) => {
  let { username, password } = ctx.request.body
  const user = await User.findOne({username, password})

  if (!user) {
    ctx.body = {
      error: true,
      message: '用户名或密码错误',
    }
    return
  }
  ctx.body = {
    error: false,
    data: {
      username: user.username,
    }
  }
})

router.get('/notices', async(ctx, next) => {
  const data = await Notice.find({})
  ctx.body = data
})

module.exports = router